package com.unione.unione_base.util;

/**
 * 字节工具类
 *
 * @author 袁攀
 */
public final class ByteUtils {
    /**
     * 将int类型的数据转为2个字节长度的字节数组
     *
     * @param value int值
     * @return 2个字节长度的字节数组
     */
    public static byte[] to2Bytes(int value) {
        return new byte[]{
                (byte) (value >> 8 & 0xff),
                (byte) (value & 0xff)
        };
    }

    public static byte[] to2BytesMin(int value) {
        return new byte[]{
                (byte) (value & 0xff),
                (byte) (value >> 8 & 0xff)
        };
    }

    /**
     * 将字节数组转化为十六进制字符串
     *
     * @param data 字节数组
     * @return 十六进制字符串
     */
    public static String bytesToHexString(byte[] data) {
        return bytesToHexString(data, false);
    }

    /**
     * 将字节数组转化为十六进制字符串
     *
     * @param data      字节数组
     * @param showBlank 是否用空格分隔
     * @return 十六进制字符串
     */
    public static String bytesToHexString(byte[] data, boolean showBlank) {
        StringBuilder stringBuilder = new StringBuilder();
        final int len = data.length;
        for (int i = 0; i < len; i++) {
            stringBuilder.append(String.format("%02x", data[i]));
            if (showBlank && i < len - 1) {
                stringBuilder.append(' ');
            }
        }
        return stringBuilder.toString();
    }

    /**
     * 将字节数组转为int类型值
     *
     * @param bytes 字节数组
     * @return int类型值
     */
    public static int toInt(byte[] bytes) {
        int value = 0;
        for (byte b : bytes) {
            value = (value << 8) + (b & 0xFF);
        }
        return value;
    }

    /**
     * 将1个字节数组转为int类型值
     *
     * @param b 1个字节
     * @return int类型值
     */
    public static int toInt(byte b) {
        return toInt(new byte[]{b});
    }

    /**
     * 16进制字符串转byte数组
     *
     * @param inHex
     * @return
     */
    public static byte[] hexToBytes(String inHex) {

        String[] hex = inHex.split("\\s");//将接收的字符串按空格分割成数组
        byte[] byteArray = new byte[hex.length];

        for (int i = 0; i < hex.length; i++) {
            //parseInt()方法用于将字符串参数作为有符号的n进制整数进行解析
            byteArray[i] = (byte) Integer.parseInt(hex[i], 16);
        }

        return byteArray;

    }

    public static byte[] concatBytes(byte[] arr1, byte[] arr2) {
        byte[] arr = new byte[arr1.length + arr2.length];
        System.arraycopy(arr1, 0, arr, 0, arr1.length);
        System.arraycopy(arr2, 0, arr, arr1.length, arr2.length);
        return arr;
    }

    public static int[] intToBinary(int value) {
        String binaryString = Integer.toBinaryString(value);
        char[] chars = binaryString.toCharArray();
        int[] intValues = new int[chars.length];
        for (int i = 0; i < chars.length; i++) {
            intValues[i] = chars[i] == '1' ? 1 : 0;
        }

        return intValues;
    }
}
